package com.gaogzhen.security.lock.reentrant;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "w.TestCondition")
public class TestCondition {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock room = new ReentrantLock();
        // 是否又电
        AtomicBoolean hasElectric = new AtomicBoolean(false);
        // 是否有柴油
        boolean hasDiesel = false;
        // 等电的休息室
        Condition electric = room.newCondition();
        // 等柴油的休息室
        Condition diesel = room.newCondition();
        new Thread(() -> {

            room.lock();
            try {
                log.debug("电有了没？[{}]", hasElectric);
                while (!hasElectric.get()) {
                    log.debug("没电，先歇会！");
                    try {
                        electric.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("电接通了？[{}]", hasElectric);
                if (hasElectric.get()) {
                    log.debug("开始干活！");
                }
            } finally {
                room.unlock();
            }

        }, "李师傅").start();

        new Thread(() -> {

            room.lock();
            try {
                log.debug("柴油送到没？[{}]", hasElectric);
                while (!hasDiesel) {
                    log.debug("柴油没送到，先歇会！");
                    try {
                        diesel.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("柴油送到没？[{}]", hasElectric);
                if (hasDiesel) {
                    log.debug("开始干活！");
                }

            } finally {
                room.unlock();
            }
        }, "王师傅").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(() -> {
            try {
                room.lock();
                hasElectric.set(true);
                log.debug("电接通了！");
                electric.signal();
            } finally {
                room.unlock();
            }
        }, "工人").start();
    }
}
